package com.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.common.ajax.AjaxRes;
import com.common.mybatis.Page;
import com.common.utils.base.Const;
import com.controller.base.BaseController;
import com.entity.Complaint;
import com.entity.User;
import com.service.ComplaintService;

@Controller
@RequestMapping("complaint")
public class ComplaintController extends BaseController<Complaint>{

	@Autowired
	private ComplaintService complaintService;
	
	@RequestMapping("index")
	public String index(){
		return "pages/complaint/complaint";
	}
	
	@RequestMapping("/info")
	@ResponseBody
	public AjaxRes info(Complaint complaint, Page<Complaint> pages){
		AjaxRes res = new AjaxRes();
		pages = complaintService.findByPage(complaint, pages);
		res.setSucceed(pages, Const.DATA_SUCCEED);
		return res;
	}
	
	@RequestMapping("/detail")
	@ResponseBody
	public AjaxRes detail(Complaint complaint){
		AjaxRes res = new AjaxRes();
		complaint = complaintService.find(complaint).get(0);
		res.setSucceed(complaint, Const.DATA_SUCCEED);
		return res;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public AjaxRes add(@RequestBody Map<String,Object> map){
		AjaxRes res = new AjaxRes();
		//Map 转为JSON 再反序列化为bean
		String json = JSONArray.toJSONString(map.get("obj"));
		Complaint complaint = JSON.parseArray(json, Complaint.class).get(0);
		if(complaint.getAnonymityState() == 2){
			User u = (User) getRequest().getSession().getAttribute("loggedIn");
			complaint.setComplainantId(u.getId());
		}else complaint.setComplainantId("anonymous");
		complaint.setComplaintState(1);
		complaintService.insert(complaint);
		res.setSucceedMsg(Const.SAVE_SUCCEED);
		return res;
	}
	
	@RequestMapping("/upd")
	@ResponseBody
	public AjaxRes upd(@RequestBody Map<String,Object> map){
		AjaxRes res = new AjaxRes();
		String json = JSONArray.toJSONString(map.get("obj"));
		Complaint complaint = JSON.parseArray(json, Complaint.class).get(0);
		complaintService.update(complaint);
		res.setSucceedMsg(Const.UPDATE_SUCCEED);
		return res;
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public AjaxRes del(Complaint complaint){
		AjaxRes res = new AjaxRes();
		complaintService.delete(complaint);
		res.setSucceed(Const.DEL_SUCCEED);
		return res;
	}
	
	@RequestMapping("/delBatch")
	@ResponseBody
	public AjaxRes delBatch(@RequestBody List<Complaint> complaints){
		AjaxRes res = new AjaxRes();
		complaintService.deleteBatch(complaints);
		res.setSucceed(Const.DEL_SUCCEED);
		return res;
	}
}
